<!DOCTYPE html>
<html>
<head>
<script>
var req;
var doc;
var newItems;
var oldItems;
var starItems; // Newly updated items
var initialized;
var feedUrl = 'http://feeds.feedburner.com/DrudgeReportFeed';

function begin() {
	initialized = false;
	starItems = [];
	localStorage["numberStories"] = 100;
	localStorage["refreshRate"] = 1;
	startRequest();
}

function startRequest() {
	updateFeed();
	if (doc) {
		updateBadge();
		initialized = true;
		timerId = window.setTimeout(startRequest, 60000 * localStorage["refreshRate"]);
	} else {
		timerId = window.setTimeout(startRequest, 500);
	}
}

function updateFeed() {
	req = new XMLHttpRequest();
	req.onload = handleResponse;
	req.open("GET", feedUrl, true);
	req.send(null);
}

function handleResponse() {
	doc = req.responseXML;
}

function updateBadge() {
	updateNewItems();
	compareItems();
	if (starItems.length > 0) {
		chrome.browserAction.setBadgeText({text:String(starItems.length)});
	} else {
		chrome.browserAction.setBadgeText({text:""});
	}
}

function updateNewItems() {
	var newElements = doc.getElementsByTagName('item');
	newItems = new Array(newElements.length);
	for (var i = 0; i < newElements.length; i++) {
		newItems[i] = newElements.item(i).getElementsByTagName('description')[0].textContent;
		newItems[i] = newItems[i].substring(0, newItems[i].indexOf("<a href"));
	}
}

function updateOldItems() {
	oldItems = new Array(newItems.length);
	for (var i = 0; i < newItems.length; i++) {
		oldItems[i] = newItems[i];
	}
}

function compareItems() {
	if (oldItems) {
		var found;
		starItems = [];
		for (var x = 0; x < newItems.length; x++) {
			found = false;
			for (var y = 0; y < oldItems.length; y++) {
				if (newItems[x] == oldItems[y]) {
					found = true;
				}
			}
			if (!found) {
				starItems.push(newItems[x]);
			}
		}
	} else {
		starItems = new Array(newItems.length);
			for (var i = 0; i < newItems.length; i++) {
				starItems[i] = newItems[i];
			}
		updateOldItems();
	}
}
</script>
</head>
<body onload="begin()">
</body>
</html>